<template>
  <el-dialog :title="showTitle" :visible="showDialog" @close="onCancel">
    <el-form ref="formRef" :model="formModel" :rules="rules" style="width:100%" label-width="120px">
      <el-form-item prop="name" label="部门名称">
        <el-input v-model="formModel.name" placeholder="2-10个字符" style="width: 80%" size="mini" />
      </el-form-item>
      <el-form-item prop="code" label="部门编码">
        <el-input v-model="formModel.code" placeholder="2-10个字符" style="width: 80%" size="mini" />
      </el-form-item>
      <el-form-item prop="managerId" label="部门负责人">
        <el-select v-model="formModel.managerId" placeholder="请选择负责人" style="width: 80%" size="mini">
          <el-option v-for="item in managerList" :key="item.id" :label="item.username" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item prop="introduce" label="部门介绍">
        <el-input v-model="formModel.introduce" placeholder="1-100个字符" :rows="4" type="textarea" style="width: 80%" size="mini" />
      </el-form-item>
      <el-form-item>
        <el-row type="flex" justify="center">
          <el-col :span="12">
            <el-button size="mini" type="primary" @click="onSubmit">确认</el-button>
            <el-button size="mini" @click="onCancel">取消</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { departmentGetService, departmentManagerService, departmentAddService, departmentDetailService, departmentUpdateService } from '@/api/department' // 引入部门管理接口
export default {
  props: {
    showDialog: Boolean,
    currentNodeId: {
      // 获取当前所编辑的节点id
      type: Number,
      required: true
    }
  },
  data() {
    return {
      managerList: [],
      formModel: {
        code: '',
        name: '',
        managerId: '',
        pid: '',
        introduce: ''
      },
      rules: {
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
          {
            // 自定义校验规则，判断部门编码是否已存在
            trigger: 'blur',
            validator: async(rule, value, callback) => {
              let res = await departmentGetService()
              if (this.formModel.id) {
                // 编辑部门时，排除当前部门编码
                res = res.filter(item => item.id !== this.formModel.id)
              }
              if (res.some(item => item.code === value)) {
                callback(new Error('部门编码已存在'))
              } else {
                callback()
              }
            }
          }
        ],
        managerId: [
          { required: true, message: '请选择负责人', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10', trigger: 'blur' },
          {
            // 自定义校验规则，判断部门名称是否已存在
            trigger: 'blur',
            validator: async(rule, value, callback) => {
              let res = await departmentGetService()
              if (this.formModel.id) {
                // 编辑部门时，排除当前部门名称
                res = res.filter(item => item.id !== this.formModel.id)
              }
              if (res.some(item => item.name === value)) {
                callback(new Error('部门名称已存在'))
              } else {
                callback()
              }
            }
          }
        ]
      }
    }
  },
  computed: {
    showTitle() {
      return this.formModel.id ? '编辑部门' : '添加部门'
    }
  },
  async created() {
    this.managerList = await departmentManagerService()
  },
  methods: {
    onCancel() {
      // 注意：resetFields只会重置模板中原先就有的值，不会重置传入模板的值
      this.formModel = {
        code: '',
        name: '',
        managerId: '',
        pid: '',
        introduce: ''
      }
      this.$refs.formRef.resetFields() // 重置表单
      this.$emit('update:showDialog', false)
    },
    onSubmit() {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          if (this.formModel.id) {
            // 编辑部门
            await departmentUpdateService(this.formModel)
          } else {
            await departmentAddService({ ...this.formModel, pid: this.currentNodeId })
          }
          this.$message({
            type: 'success',
            message: `${this.formModel.id ? '编辑' : '添加'}部门成功`
          })
          this.onCancel()
          this.$emit('updateDepartment')
        }
      })
    },
    async getDeptDetail() {
      this.formModel = await departmentDetailService(this.currentNodeId)
    }
  }
}
</script>
